package com.atguigu.user.service.impl;

import com.atguigu.pojo.Address;
import com.atguigu.user.mapper.AddressMapper;
import com.atguigu.user.service.AddressService;
import com.atguigu.utils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 张三禾
 * @create 2023-03-11 13:51
 * @Description 地址业务实现类
 */
@Slf4j
@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;
    /**
     * 根据用户id查询地址数据
     * @param  userId 用户id校验完毕
     * @return 001 004
     */
    @Override
    public R list(Integer userId) {
        //1. 封装查询参数
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);

        List<Address> addresseList = addressMapper.selectList(queryWrapper);

        //2. 结果封装
        R ok = R.ok("查询成功",addresseList);
        log.info("AddressServiceImpl.list业务结束，结果：{}", ok);
        return ok;
    }

    /**
     * 插入地址数据，成功后返回更新的数据集合
     * @param address 数据校验完毕
     * @return
     */
    @Override
    public R save(Address address) {
        //1. 插入数据
        int rows = addressMapper.insert(address);
        //2. 插入成功
        if (rows == 0){
            log.info("AddressServiceImpl.save业务结束，结果：{}", "地址失败！");
            return R.fail("插入地址失败！");
        }
        //3. 复用查询业务
        return list(address.getUserId());
    }

    /**
     * TODO:
     *  1. 定义接受参数的param，并且添加参数校验注解
     *  2. 定义Controller
     *  3. 定义service
     *  4. 定义mapper
     * 根据id删除地址数据
     * @param id 地址id
     * @return 001 004
     */
    @Override
    public R remove(Integer id) {
        int rows = addressMapper.deleteById(id);
        if(rows == 0){
            log.info("AddressServiceImpl.remove业务结束，结果：{}", "删除地址数据失败");
            return R.fail("删除地址数据失败！");
        }
        log.info("AddressServiceImpl.remove业务结束，结果：{}", "删除数据成功");
        return R.ok("地址删除成功");

    }


}
